import { createRouter, createWebHashHistory } from 'vue-router'
import _axios from '../utils/myAxios.js'
import { ref } from 'vue'
import { useMenuStore } from '../store/menu.js'
import { start, close } from '../utils/nprogress.js'
const routers = ref([])
let flag = ref(true)

let routes = [
  { //默认跳到首页
    path: '/' || '',
    redirect: '/home'
  },

  { //登录页
    path: '/login',
    name: 'login',
    component: () => import('../views/login/index.vue')
  },
  { //前台布局页
    path: '/home',
    name: 'home',
    component: () => import('../components/layout/index.vue'),
    redirect: '/index',
    children: [
      { //首页
        path: '/index',
        name: 'index',
        redirect: '/latest',
        component: () => import('../views/index/index.vue'),
        children: [
          { //最新
            path: '/latest',
            name: 'latest',
            component: () => import('../views/index/latest/index.vue')
          },
          { //推荐
            path: '/recommended',
            name: 'recommended',
            component: () => import('../views/index/recommended/index.vue')
          },
          { //我的
            path: '/mine',
            name: 'mine',
            component: () => import('../views/index/mine/index.vue')
          },
          { //视频
            path: '/video',
            name: 'video',
            component: () => import('../views/index/video/index.vue')
          }
        ]
      },
      { //教育页
        path: '/education',
        name: 'education',
        component: () => import('../views/education/index.vue')
      },

      { //多人聊天室
        path: '/chatRoom',
        name: 'chatRoom',
        component: () => import('../views/chatRoom/index.vue')
      },
      { //AI
        path: '/AIHome',
        name: 'AIHome',
        component: () => import('../views/ai/Home.vue'),
      },
      { //ai助手小团团
        path: '/AIChat',
        name: 'AIChat',
        component: () => import('../views/ai/AIChat.vue')
      },
      { //哄哄模拟器
        path: '/AIGame',
        name: 'AIGame',
        component: () => import('../views/ai/GameChat.vue')
      },
      {//文章详情页
        path: '/detailArticle',
        name: 'detailArticle',
        component: () => import('../views/detailArticle/index.vue')
      }, { //搜索页
        path: '/search',
        name: 'search',
        component: () => import('../views/search/index.vue')
      },
    ]
  },
  { //后台页面布局
    path: '/backstage',
    name: 'backstage',
    component: () => import('../components/layout/backstageIndex.vue'),
    redirect: '/backIndex',
    children: [
      {
        path: '/backIndex',
        name: 'backIndex',
        component: () => import('../views/backstage/index.vue')
      },
    ]
  },
  { //用户信息页
    path: '/userInfo',
    name: 'userInfo',
    component: () => import('@/views/userInfo/index.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/home'
  }
]

const useRouter = createRouter({
  history: createWebHashHistory(),
  routes,
})

useRouter.beforeEach(async (to, from, next) => {
  start()
  const menuStore = useMenuStore()
  let authorization = localStorage.getItem('Authorization')
  // let authorization = localStorage.getItem('Authorization') || sessionStorage.getItem('Authorization')
  if (authorization && to.path === '/login') {
    next({ path: '/home' })
    return
  } else if (!authorization && to.path !== '/login') {
    next({ path: '/login' })
    return
  } else if ((to.path === '/detailArticle' && to.query.articleId === undefined) ||
    (to.path === '/detailArticle' && to.query.articleId === null) ||
    (to.path === '/detailArticle' && to.query.articleId === '')) {
    next({ path: '/home' })
    return
  } else if (to.path.startsWith('/back')) {
    if (menuStore.length) {
      let res = await _axios.get("/api/menu/getRouters")
      menuStore.menu = res.data.data
      addRouter(menuStore, menuStore.menu)
      routers.value.forEach((r) => {
        useRouter.addRoute("backstage", r)
      })
      addRouterchildren(menuStore.menu)
      menuStore.children = routers.value
      menuStore.children.push('/backIndex')
      flag = menuStore.children.includes(to.path)
      routers.value = []
    } else {
      addRouterchildren(menuStore.menu)
      menuStore.children = routers.value
      menuStore.children.push('/backIndex')
      flag = menuStore.children.includes(to.path)
      routers.value = []
    }
    if (!flag) {
      next({ path: '/home' })
    }
    next()
  } else {
    next()
  }
})

useRouter.afterEach(() => {
  close()
})
async function addRouter(menuStore, res) {
  for (let i = 0; i < res.length; i++) {
    let child = res[i]
    if (child.children.length > 0 || child.childern !== null) {
      addRouter(menuStore, child.children)
    }
    if (child.component) {
      routers.value.push({
        path: child.path,
        component: () => import(`@/views/backstage/${child.component}.vue`)
      });
    }
  }
}
async function addRouterchildren(res) {
  for (let i = 0; i < res.length; i++) {
    let child = res[i]
    if (child.children.length > 0 || child.childern !== null) {
      addRouterchildren(child.children)
    }
    if (child.component) {
      routers.value.push(child.path);
    }
  }
}

export default useRouter